package com.wxy.ej.nosql.config.resource;

import com.wxy.ej.nosql.config.resource.exception.AuthExceptionEntryPoint;
import com.wxy.ej.nosql.config.resource.exception.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.boot.autoconfigure.security.oauth2.authserver.AuthorizationServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.*;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(AuthorizationServerProperties.class)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    //配置当前资源服务器的ID
    public static final String RESOURCE_ID = "product-server";

    @Autowired
    private TokenStore jwtTokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        //resource资源只允许基于令牌的身份验证
        resources.resourceId(RESOURCE_ID).tokenServices(tokenService());
        // .tokenStore(jwtTokenStore);
        //resources.resourceId("product").stateless(true);
        //resources.tokenServices(resourceJwtTokenServices);

        //这里把自定义异常加进去
        resources
                .tokenStore(jwtTokenStore)
                .authenticationEntryPoint(new AuthExceptionEntryPoint())
                .accessDeniedHandler(new CustomAccessDeniedHandler());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                // 由于我们希望在用户界面中访问受保护的资源，因此我们需要允许创建会话
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .requestMatchers().anyRequest()
                .and()
                //启用匿名登录，不可访问受保护资源
                .anonymous()
                .and()
                .authorizeRequests()
                //配置protected访问控制，必须认证过后才可以访问
                .antMatchers("/base/**").authenticated();
    }

    /**
     * 配置资源服务器如何验证token有效性
     * 1. DefaultTokenServices
     * 如果认证服务器和资源服务器同一服务时,则直接采用此默认服务验证即可
     * 2. RemoteTokenServices (当前采用这个)
     * https://www.jianshu.com/p/6dd03375224d
     */

    @Autowired
    private OAuth2ClientProperties oAuth2ClientProperties;
    @Autowired
    private AuthorizationServerProperties authorizationServerProperties;

    @Bean
    public ResourceServerTokenServices tokenService() {
        /*// 资源服务器去远程认证服务器验证 token 是否有效
        RemoteTokenServices service = new RemoteTokenServices();
        // 请求认证服务器验证URL，注意:默认这个端点是拒绝访问的，要设置认证后可访问
        service.setCheckTokenEndpointUrl("http://127.0.0.1:9997/auth/oauth/check_token");
        // 在认证服务器配置的客户端id
        service.setClientId("mengxuegu-pc");
        // 在认证服务器配置的客户端密码
        service.setClientSecret("mengxuegu-secret");
        return service;*/
        // 数据读取配置文件
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl(authorizationServerProperties.getCheckTokenAccess());
        remoteTokenServices.setClientId(oAuth2ClientProperties.getClientId());
        remoteTokenServices.setClientSecret(oAuth2ClientProperties.getClientSecret());
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
        return remoteTokenServices;
    }

    @Bean
    public AccessTokenConverter accessTokenConverter() {
        return new DefaultAccessTokenConverter();
    }

}
